package edu.neusoft.springmvc.controller;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import edu.neusoft.springmvc.model.TestModel;
import edu.neusoft.springmvc.model.User;

@Controller
@RequestMapping("/session")
@SessionAttributes(value = { "testModel" })
public class SessionController {

  @ModelAttribute("testModel")
  public TestModel getTestModel() {
    return new TestModel("111", "222", "333", "444");
  }

  @RequestMapping("/testmodel1")
  public ModelAndView testModel1(ModelAndView mv) {
    mv.setViewName("redirect:/session/testmodel2");
    return mv;
  }

  @RequestMapping("/testmodel2")
  public String testModel2(ModelMap map, HttpSession session) {
    TestModel model1 = (TestModel) map.get("testModel");
    TestModel model2 = (TestModel) session.getAttribute("testModel");
    System.out.println(model1.getStr1() + "-" + model1.getStr2());
    System.out.println(model2.getStr1() + "-" + model2.getStr2());
    return "success";
  }

  @ModelAttribute("user")
  public User getUser() {
    User user = new User();
    user.setUsername("zhangsan");
    user.setPassword("hello");
    user.setAge("34");
    return user;
  }

  //http://localhost:8080/spring02/session/test1?username=lisi
  @RequestMapping("/test1")
  public ModelAndView test1(@ModelAttribute("user") User user, ModelAndView mv) {
    System.out.println(user.getUsername() + "-" + user.getPassword() + "-" + user.getAge());
    //user.setUsername("lisi");
    mv.setViewName("redirect:/session/test2");
    return mv;
  }

  @RequestMapping("/test2")
  public String test2(ModelMap map) {
    User user = (User) map.get("user");
    System.out.println(user.getUsername() + "-" + user.getPassword() + "-" + user.getAge());

    return "success";
  }

  @RequestMapping("/testmodel")
  public String testModelAttribute(ModelMap map) {
    User user = (User) map.get("user");

    System.out.println(user.getUsername() + "-" + user.getPassword() + "-" + user.getAge());
    return "success";
  }

}
